package com.yonyou.brigade.third_parties.zhjw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.order_center.service.IBriOrderService;
import com.yonyou.brigade.third_parties.zhjw.model.ZhjwConfig;
import com.yonyou.brigade.third_parties.zhjw.service.IZhjwOrderService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.JsonUtils;
import com.yonyou.brigade.util.operateutil.MD5Util;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ZhjwOrderServiceImpl implements IZhjwOrderService {

    private static Logger logger = LoggerFactory.getLogger(ZhjwOrderServiceImpl.class);

    @Value("${zhjw.orderUrl}")
    private String orderUrl;

    @Value("${zhjw.tradeFlightType}")
    private String zhjwTradeFlightType;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;

    @Value("${cnv.register.userId}")
    private String cnvRegisterUserId;

    @Value("${cnv.register.tenant}")
    private String cnvRegisterTenant;

    @Value("${cnv.register.cookie}")
    private String cnvRegisterCookie;

    @Autowired
    private IConvertService convertService;

    @Autowired
    private IBriOrderService briOrderService;

    @Autowired
    private IMongoDao mongoDao;

    /**
     * 拉取中航金网订单数据
     * @param zhjwConfig
     * @param tenant
     * @param begin
     * @param end
     * @param channelId
     */
    @Override
    public void getZhjwOrders(ZhjwConfig zhjwConfig, String tenant, String begin, String end, Integer channelId) {
        String timeStamp = String.valueOf(System.currentTimeMillis());
        String sign = MD5Util.encodePassword(zhjwConfig.getKey() + begin + end + zhjwConfig.getAccountIdsStr() + timeStamp + zhjwConfig.getSecurityValue());
        JSONObject param = new JSONObject();
        String result = HttpClientUtil.doPostJson(orderUrl + "?key=" + zhjwConfig.getKey() + "&date_from=" + begin + "&date_to=" + end + "&accountIdsStr=" + zhjwConfig.getAccountIdsStr() + "&time_stamp=" + timeStamp + "&sign=" + sign, JSON.toJSONString(param));
        if (!StringUtils.isEmpty(result) && JsonUtils.isJSONObject(result)) {
            JSONObject resultJSON = JSONObject.parseObject(result);
            if ("true".equals(resultJSON.getString("successState"))){
                if (CollectionUtils.isEmpty(resultJSON.getJSONArray("model"))) {
                    logger.error("拉取中航金网订单失败，model为空");
                    return;
                }
                for (Object model : resultJSON.getJSONArray("model")) {
                    if (!JsonUtils.isJSONObject(JSON.toJSONString(model))) {
                        logger.error("model不能转成JSONObject：" + JSON.toJSONString(model));
                    }
                    JSONObject modelJSON = (JSONObject) model;
                    JSONArray orderlistList = modelJSON.getJSONArray("orderlistList");
                    if (!CollectionUtils.isEmpty(orderlistList)) {
                        convertAndSave(orderlistList, tenant, channelId);
                    }
                }
            } else {
                logger.error("拉取中航金网订单失败");
            }

        }
    }

    private void convertAndSave(JSONArray orderList, String tenantId, Integer channelId) {
        for (Object order : orderList) {
            if (JsonUtils.isJSONObject(JSON.toJSONString(order))) {
                JSONObject orderJSON = (JSONObject) order;
                try {
                    dealWithMongo("zhjw_flight_orders", orderJSON);
                } catch (Exception e) {
                    logger.error("中航金网订单存入mongo异常");
                }
                JSONObject res = convertService.convert(zhjwTradeFlightType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, orderJSON);
                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null && orderCenter.size() > 0) {
                                String orderNo = orderCenter.getString("orderNo") + "_" + orderJSON.getString("ticketNo") + "_" + orderJSON.getString("ticketstate");
                                String userId = orderCenter.getString("userId");
                                try {
                                    briOrderService.saveFlight(orderCenter, orderNo, tenantId, userId, ChannelEnum.ZHJW.getName(), channelId);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    logger.error("中航金网机票存入订单中心时，出现异常：" + e.getMessage());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void dealWithMongo(String mongoName, JSONObject orderJson) {
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("ordernumber", orderJson.getString("ordernumber"));
        criteriaMap.put("id", orderJson.getString("id"));
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, mongoName);
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, mongoName);
            mongoDao.getMongoTemplate().save(orderJson, mongoName);
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson, mongoName);
        }
    }
}
